package org.ru.mse10.cvis.upload;

import java.util.ResourceBundle;

import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.naming.NamingException;

import org.ru.mse10.cvis.entity.cv.User;
import org.ru.mse10.cvis.service.MailService;
import org.ru.mse10.cvis.service.UserService;
import org.ru.mse10.cvis.util.CommonUtil;

/**
 * Class that handle the current user.
 * 
 * @author Spawn
 * 
 */
public class UserXMLRowHandler extends CommonHandler<User> {

	/** The context. */
	private final FacesContext context = FacesContext.getCurrentInstance();

	/** The bundle. */
	private final ResourceBundle bundle = context.getApplication()
			.getResourceBundle(context, "message");

	/**
	 * Method to handle the current user read from xml file.
	 * 
	 * @param user
	 *            the user
	 */
	@Override
	public void handle(User user) {
		try {
			UserService userService = CommonUtil
					.lookupService(UserService.class);
			MailService mailService = CommonUtil
					.lookupService(MailService.class);
			if (userService.isExistingUserEmail(user.getEmail())) {
				FacesContext.getCurrentInstance().addMessage(
						"uploadForm",
						new FacesMessage(FacesMessage.SEVERITY_ERROR, bundle
								.getString("errorUploadFileMail"), null));
			} else {
				String password = setPasswordToUser(user);
				userService.saveInNewTx(user);
				String subject = "You have been registered in CVIS!";
				String mailText = "You have been registered in CVIS!\nTo access the system use the following credentials:\nUsername: "
						+ user.getEmail() + "\nPassword: " + password;
				mailService.sendUserMail(password, user.getEmail(), subject,
						mailText);
			}
		} catch (NamingException e1) {
			e1.printStackTrace();
		}
	}
}
